package com.vivimice.lotroller.device;

import java.util.Map;

import com.vivimice.lotroller.notification.NotificationAgent;
import com.vivimice.lotroller.notification.NotificationType;

/**
 * A device sends specified notification when triggered
 * 
 * If the status of the upper device is true, positive notification is sent,
 * otherwise negative notification is sent.
 * 
 * OutputDevice will bring the data map from upper device along with the notification
 * as the data part.
 * 
 * @author vivimice
 *
 */
public class OutputDevice extends Device {

	private NotificationAgent agent;
	private NotificationType positiveType;
	private NotificationType negativeType;
	private Device upperDevice;
	
	public OutputDevice(Device upperDevice, NotificationAgent agent, 
			NotificationType positiveType, NotificationType negativeType) {
		this.upperDevice = upperDevice;
		this.agent = agent;
		this.positiveType = positiveType;
		this.negativeType = negativeType;
		
		if (!this.upperDevice.hasNextDevice()) {
			this.upperDevice.setNextDevice(this);	
		} else {
			throw new IllegalStateException("Upper device is already associated to another device");
		}
	}
	
	public OutputDevice(Device upperDevice, NotificationAgent agent, NotificationType positiveType) {
		this(upperDevice, agent, positiveType, null);
	}
	
	@Override
	protected void trigger() {
		boolean status = getStatus();
		if (status && positiveType != null) {
			agent.sendNotification(positiveType, getDataMap());
		} else if (!status && negativeType != null) {
			agent.sendNotification(negativeType, getDataMap());
		}
	}
	
	@Override
	public boolean getStatus() {
		return upperDevice.getStatus();
	}

	@Override
	public Map<NotificationType, Object> getDataMap() {
		return upperDevice.getDataMap();
	}

	@Override
	public void close() {
		upperDevice.close();
	}
	
}
